package com.wh.interceptors;

import cn.hutool.core.util.StrUtil;
import com.wh.common.Constant;
import com.wh.config.RedisCache;
import com.wh.exception.SytException;
import com.wh.exception.SytExceptionEnum;
import com.wh.util.JwtUtil;
import com.wh.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2022/11/17 9:43
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    /**
     * 添加前置拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的token
        String token = request.getHeader("token");
        // 2.如果为空则拦截
        if (StrUtil.isBlank(token)) {
            throw new SytException(SytExceptionEnum.NEED_LOGIN);
        }
        String jwtToken = null;
        Long expire = 0L;
        //判断当前token是否过期，以及是否和redis中对应的reToken一致
        //   boolean verify = JwtUtil.verify(token);
        try {
            expire = JwtUtil.getExpire(token);
        } catch (Exception e) {
            throw new SytException(SytExceptionEnum.TOKEN_FAILD);
        }
        //如果当前token过期，则从redis查询对应的reToken信息进行刷新
        if (System.currentTimeMillis() > expire * 1000){
            String userId = JwtUtil.getJti(token);
            Object object = redisUtil.get(userId);
            if (object.equals(null)){
                throw new SytException(SytExceptionEnum.TOKEN_FAILD);
            }else {
                //解析reToken是否过期，如果过期则需要清除redis缓存,然后要求重新登录。没有过期则利用reToken再次生成access_token
                Long expireTime = JwtUtil.getExpire(object.toString());
                if(System.currentTimeMillis() > expireTime * 1000){
                    redisUtil.del(userId);
                    throw new SytException(SytExceptionEnum.NEED_RELOGIN);
                }
                //刷新access_Token
                jwtToken = JwtUtil.createJWT(userId, Constant.ACCTOKEN_EXPIRE_TIME * 1000);
                //刷新redis中reToken的过期时间
                redisUtil.set(userId,(String)object,Constant.RETOKEN_EXPIRE_TIME );
                System.out.println(jwtToken);
            }
        }
        return true;
    }
}
